package com.lagou.chat;

import com.lagou.netty.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class NettyChatClient {

    public static void main(String[] args) throws InterruptedException {
        NettyChatClient nettyChatClient = new NettyChatClient("127.0.0.1", 9999);
        nettyChatClient.run();
    }

    private String ip;

    private int port;

    public NettyChatClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void run() throws InterruptedException {
        //1. 创建一个线程组
        EventLoopGroup eventLoopGroup = null;
        try {
            eventLoopGroup = new NioEventLoopGroup();
            //2. 创建一个启动助手
            Bootstrap bootstrap = new Bootstrap();
            //3. 注册线程组
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)//4. 设置客户端通道实现为NIO
                    .handler(new ChannelInitializer<SocketChannel>() {//5. 创建一个通道初始化对象
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {//6. 配置自定义拦截器
                            ChannelPipeline pipeline = ch.pipeline();
                            //加入编解码器
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new StringDecoder());
                            //加入处理器
                            pipeline.addLast(new NettyChatClientHandler());
                        }
                    });
            //7. 启动客户端, 等待连接服务端, 同时将异步改为同步
            ChannelFuture future = bootstrap.connect(ip, port).sync();
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        System.out.println("服务端连接成功========");
                    } else {
                        System.out.println("服务端连接失败========");
                    }
                }
            });
            Channel channel = future.channel();
            //通过通道给聊天室发送消息
            Scanner scanner = new Scanner(System.in);
            System.out.println("----------" + channel.localAddress().toString() + "-------------");
            while (scanner.hasNext()) {
                channel.writeAndFlush(scanner.nextLine());
            }
            //8. 关闭通道(不是真正意义上的关闭,而是一直监听通道关闭状态),异步改同步
            channel.closeFuture().sync();
        } finally {
            //9. 关闭线程组
            eventLoopGroup.shutdownGracefully();
        }

    }
}
